package com.walkline.screen;

import java.util.Hashtable;
import java.util.Vector;

import localization.WeiboSDKResource;
import net.rim.device.api.i18n.ResourceBundle;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.util.StringProvider;

import com.walkline.screen.ShowStatusesMainScreen.SetRemindsCountCallback;
import com.walkline.util.Enumerations.RefreshAction;
import com.walkline.util.Enumerations.RemindType;
import com.walkline.util.Function;
import com.walkline.util.container.ForegroundManager;
import com.walkline.util.container.UserInfoListStyleButtonSet;
import com.walkline.util.container.VerticalButtonFieldSet;
import com.walkline.util.network.DownloadUserAvatarImages;
import com.walkline.util.network.WorkQueue;
import com.walkline.util.ui.UserInfoListStyleButtonField;
import com.walkline.weibo.BasicAsyncCallback;
import com.walkline.weibo.WeiboSDK;
import com.walkline.weibo.inf.User;
import com.walkline.weibo.inf.UserWrapper;

/**
 * 显示用户好友或粉丝列表窗口
 */
public class ShowFriendshipMainScreen extends MainScreen implements WeiboSDKResource
{
	private static ResourceBundle _bundle = ResourceBundle.getBundle(BUNDLE_ID, BUNDLE_NAME);

	private WeiboSDK _weibo;
	private WorkQueue _queue = new WorkQueue(2);
	private ForegroundManager _foreground = new ForegroundManager(0);
	private UserInfoListStyleButtonSet _listSet = new UserInfoListStyleButtonSet();
	private UserInfoListStyleButtonField _item;
	private Hashtable _params = new Hashtable();
	private ButtonField _btnMore = new ButtonField("更多", ButtonField.CONSUME_CLICK | ButtonField.NEVER_DIRTY);
	private VerticalButtonFieldSet vbf = new VerticalButtonFieldSet(USE_ALL_WIDTH);

	private int _type = 0;
	private String _current_cursor = "0";
	private String _remindType = "";

	public ShowFriendshipMainScreen(WeiboSDK weibo,final Hashtable params, int type)
	{
		super(NO_VERTICAL_SCROLL | USE_ALL_HEIGHT | NO_SYSTEM_MENU_ITEMS);

		_weibo = weibo;
		_type = type;
		_params = params;

		_listSet.setMargin(0, -1, 0, -1);

		HorizontalFieldManager hfmTitle = new HorizontalFieldManager(FIELD_HCENTER);
		hfmTitle.add(new LabelField((String) params.get("title")));
		setTitle(hfmTitle);

		_btnMore.setChangeListener(new FieldChangeListener()
		{
			public void fieldChanged(Field field, int context)
			{
				refreshNextPage();
			}
		});					
		vbf.add(_btnMore);

		UiApplication.getUiApplication().invokeLater(new Runnable()
		{
			public void run() {getUserList(params);}
		});
	}

	private void getUserList(Hashtable params)
	{
		RefreshContentsScreen popupScreen = new RefreshContentsScreen(_weibo, params, _type);
		UiApplication.getUiApplication().pushModalScreen(popupScreen);

		UserWrapper userWrapper = popupScreen.getUserWrapper();

		if (popupScreen != null) {popupScreen = null;}
		if (userWrapper != null)
		{
			resetReminds();

			refresUserList(userWrapper);
		}
	}		

	private void refresUserList(UserWrapper userWrapper)
	{
		Vector users = userWrapper.getUserList();

		if (users.size() > 0)
		{
			if (_foreground.getManager() == null) {add(_foreground);}

			User user;
			for (int i=0; i<users.size(); i++)
			{
				user = (User) users.elementAt(i);
				_item = new UserInfoListStyleButtonField(user);
				_item.setChangeListener(new FieldChangeListener()
				{
					public void fieldChanged(Field field, int context)
					{
						showUserHomepage();
					}
				});
				_listSet.add(_item);
			}
			_current_cursor = userWrapper.getNextCursor();

			if (_listSet.getManager() != _foreground) {_foreground.add(_listSet);}

			if (_listSet.getFieldCount() > 0)
			{
				UiApplication.getUiApplication().invokeLater(new Runnable()
				{
					public void run()
					{
						if (vbf.getManager() != _listSet)
						{
							_listSet.add(vbf);
						} else {
							_listSet.delete(vbf);
							_listSet.add(vbf);
						}

						refreshUserListIcons();
					}
				});
			}
		}
	}

	private void refreshUserListIcons()
    {
		UserInfoListStyleButtonField item;

		_queue.removeAll();

		for (int i=0; i<_listSet.getFieldCount(); i++)
		{
			Field object = _listSet.getField(i);

			if (object instanceof UserInfoListStyleButtonField)
			{
				item = (UserInfoListStyleButtonField) object;
				_queue.execute(new DownloadUserAvatarImages(_weibo, item));
			}
		}
    }

	private void resetReminds()
	{
		switch (_type)
		{
			case RefreshAction.USERLISTFOLLOWERS:
				_remindType = RemindType.FOLLOWER;
				break;
		}

		if (_current_cursor.equals("0"))
		{
			UiApplication.getUiApplication().invokeLater(new Runnable()
			{
				public void run()
				{
					_weibo.setRemindCount(_remindType, new SetRemindsCountCallback(), null);
				}
			});						
		}
	}

	class SetRemindsCountCallback extends BasicAsyncCallback
	{
		public void onComplete(final boolean value, Object state)
		{
			if (value)
			{
				switch (_type)
				{
					case RefreshAction.USERLISTFOLLOWERS:
						_weibo.getReminds().setFollower(0);
						break;
				}
			}
		}

		public void onException(Exception e, Object state) {Function.errorDialog(e.toString());}
	}

	/**
	 * 加载下一页内容
	 */
	private void refreshNextPage()
	{
		_params.remove("cursor");
		_params.put("cursor", _current_cursor);

		getUserList(_params);
 	}

	/**
	 * 刷新首页内容
	 */
	private void refreshHomePage()
	{
		_current_cursor = "0";

		if (_listSet.getManager() != null) {_listSet.deleteAll();}

		_params.remove("cursor");
		_params.put("cursor", "0");

		getUserList(_params);
	}

	private void showUserHomepage()
	{
		if (_listSet.getFieldCount() > 0)
		{
			UserInfoListStyleButtonField item = (UserInfoListStyleButtonField) _listSet.getFieldWithFocus();

			UiApplication.getUiApplication().pushScreen(new HomePageMainScreen(_weibo, item.getUser()));
		}
	}

	private void destroyFriendship()
	{
		if (_listSet.getFieldCount() > 0)
		{
			UserInfoListStyleButtonField item = (UserInfoListStyleButtonField) _listSet.getFieldWithFocus();

			RefreshContentsScreen popupScreen = new RefreshContentsScreen(_weibo, item.getUser().getIdStr(), RefreshAction.DESTROYFRIENDSHIP);
			UiApplication.getUiApplication().pushModalScreen(popupScreen);

			User user = popupScreen.getUserInfo();

			if (popupScreen != null) {popupScreen = null;}
			if (user != null) {refreshHomePage();}
		}
	}

	MenuItem menuRefresh = new MenuItem(_bundle, MENU_REFRESH, 100, 10)
	{
		public void run() {refreshHomePage();}
	};

	MenuItem menuUserHomepage = new MenuItem(_bundle, MENU_SHOW_USER_HOMEPAGE, 100, 20)
	{
		public void run() {showUserHomepage();} 
	};

	MenuItem menuDestroyFriendship = new MenuItem(new StringProvider("取消关注"), 100, 30)
	{
		public void run()
		{
			UserInfoListStyleButtonField item = (UserInfoListStyleButtonField) _listSet.getFieldWithFocus();

			Dialog askDialog = new Dialog(Dialog.D_YES_NO, "是否取消关注用户 " + item.getUser().getScreenName() + "？", Dialog.NO, Bitmap.getPredefinedBitmap(Bitmap.QUESTION), 0);

			UiApplication.getUiApplication().pushModalScreen(askDialog);
			if (askDialog.getSelectedValue() == Dialog.YES) {destroyFriendship();}
		}
	};

	protected void makeMenu(Menu menu, int instance)
	{
		menu.add(menuRefresh);
    	menu.addSeparator();

    	if (_listSet.getFieldCount() > 0)
    	{
    		menu.add( menuUserHomepage);
    		menu.addSeparator();
    		//menu.add(menuDestroyFriendship);
    		//menu.addSeparator();
    	}

		super.makeMenu(menu, instance);
	};

	protected boolean keyChar(char character, int status, int time)
    {
    	switch (character)
    	{
    		case Characters.SPACE:
    			if (_listSet.getFieldCount() > 0 && _listSet.getFieldWithFocusIndex() < _listSet.getFieldCount())
    			{
    				_listSet.getField(_listSet.getFieldWithFocusIndex() + 1).setFocus();
    			}
    			return true;
			case Characters.LATIN_CAPITAL_LETTER_R:
			case Characters.LATIN_SMALL_LETTER_R:
				refreshHomePage();
				return true;
			case Characters.LATIN_CAPITAL_LETTER_T:
			case Characters.LATIN_SMALL_LETTER_T:
				if (_listSet.getFieldCount() > 0) {_listSet.getField(0).setFocus();}
				return true;
			case Characters.LATIN_CAPITAL_LETTER_B:
			case Characters.LATIN_SMALL_LETTER_B:
				if (_listSet.getFieldCount() > 0) {_listSet.getField(_listSet.getFieldCount() - 1).setFocus();}
				return true;
			case Characters.LATIN_CAPITAL_LETTER_U:
			case Characters.LATIN_SMALL_LETTER_U:
				showUserHomepage();
				return true;
			case Characters.LATIN_CAPITAL_LETTER_Q:
			case Characters.LATIN_SMALL_LETTER_Q:
				Function.showExitDialog();
				return true;
		}

    	return super.keyChar(character, status, time);
    }

	public boolean onClose() 
	{
		_queue.removeAll();

		return super.onClose();
	}

	protected boolean onSavePrompt() {return true;}
}